/**
 * 数据导入导出工具
 */

export interface ExportData {
  version: string
  export_time: string
  total_count: number
  accounts: any[]
}

export interface ImportResult {
  imported: number
  skipped: number
  errors: string[]
}

/**
 * 导出为JSON文件
 */
export function exportToJsonFile(data: ExportData, filename?: string): void {
  const jsonStr = JSON.stringify(data, null, 2)
  const blob = new Blob([jsonStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)

  const defaultFilename = filename || `账号数据导出_${new Date().getTime()}.json`

  const link = document.createElement('a')
  link.href = url
  link.download = defaultFilename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

/**
 * 导出为CSV文件
 */
export function exportToCsvFile(data: any[][], filename?: string): void {
  const csvContent = data.map(row => {
    return row.map(cell => {
      // 处理包含逗号、引号或换行的字段
      const cellStr = String(cell || '')
      if (cellStr.includes(',') || cellStr.includes('"') || cellStr.includes('\n')) {
        return `"${cellStr.replace(/"/g, '""')}"`
      }
      return cellStr
    }).join(',')
  }).join('\n')

  // 添加BOM以支持中文
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)

  const defaultFilename = filename || `账号数据导出_${new Date().getTime()}.csv`

  const link = document.createElement('a')
  link.href = url
  link.download = defaultFilename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

/**
 * 读取JSON文件
 */
export function readJsonFile(file: File): Promise<ExportData> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = (e) => {
      try {
        const content = e.target?.result as string
        const data = JSON.parse(content)

        // 验证数据格式
        if (!data.version || !data.accounts || !Array.isArray(data.accounts)) {
          reject(new Error('JSON文件格式不正确'))
          return
        }

        resolve(data)
      } catch (error) {
        reject(new Error('JSON文件解析失败'))
      }
    }

    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }

    reader.readAsText(file)
  })
}

/**
 * 读取CSV文件
 */
export function readCsvFile(file: File): Promise<any[][]> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = (e) => {
      try {
        const content = e.target?.result as string
        const rows = parseCsv(content)

        if (rows.length < 2) {
          reject(new Error('CSV文件内容为空'))
          return
        }

        resolve(rows)
      } catch (error) {
        reject(new Error('CSV文件解析失败'))
      }
    }

    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }

    reader.readAsText(file)
  })
}

/**
 * 解析CSV内容
 */
function parseCsv(content: string): any[][] {
  const rows: any[][] = []
  const lines = content.split('\n')

  for (let line of lines) {
    if (!line.trim()) continue

    const row: string[] = []
    let cell = ''
    let inQuotes = false

    for (let i = 0; i < line.length; i++) {
      const char = line[i]
      const nextChar = line[i + 1]

      if (char === '"') {
        if (inQuotes && nextChar === '"') {
          // 转义的引号
          cell += '"'
          i++
        } else {
          // 切换引号状态
          inQuotes = !inQuotes
        }
      } else if (char === ',' && !inQuotes) {
        // 字段分隔符
        row.push(cell.trim())
        cell = ''
      } else {
        cell += char
      }
    }

    // 添加最后一个字段
    row.push(cell.trim())
    rows.push(row)
  }

  return rows
}

/**
 * 验证导入数据
 */
export function validateImportData(data: any): {
  valid: boolean
  errors: string[]
} {
  const errors: string[] = []

  if (!data.version) {
    errors.push('缺少版本信息')
  }

  if (!data.accounts || !Array.isArray(data.accounts)) {
    errors.push('账号数据格式错误')
  } else {
    // 验证每个账号
    data.accounts.forEach((account: any, index: number) => {
      if (!account.title) {
        errors.push(`第${index + 1}条账号缺少标题`)
      }
    })
  }

  return {
    valid: errors.length === 0,
    errors
  }
}

/**
 * 创建示例导出数据
 */
export function createSampleExportData(): ExportData {
  return {
    version: '1.0',
    export_time: new Date().toISOString(),
    total_count: 0,
    accounts: []
  }
}

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'

  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

/**
 * 下载备份文件
 */
export function downloadBackup(backupData: ExportData, filename?: string): void {
  exportToJsonFile(backupData, filename || `backup_${Date.now()}.json`)
}
